package com.franklin.ideaplugin.api.utils.psi;

import com.intellij.psi.PsiExpression;

/**
 * @author Ye Junhui
 * @since 2024/3/21
 */
public class PsiExpressionUtils {

    /**
     * 获取干净的文本
     * @param psiExpression
     * @return
     */
    public static String getCleanText(PsiExpression psiExpression){
        String text = psiExpression.getText();
        if (text.startsWith("\"")){
            text = text.substring(1);
        }
        if (text.endsWith("\"")){
            text = text.substring(0,text.length() - 1);
        }
        return parseStringCodeToString(text);
    }

    /**
     * 解析代码为字符串
     * @param code
     * @return
     */
    public static String parseStringCodeToString(String code) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < code.length(); i++) {
            char c = code.charAt(i);
            //出现转义
            if (c == '\\') {
                //往后移动一位
                char nextC = code.charAt(i + 1);
                builder.append(transformNextChar(nextC));
                i++;
            }else {
                builder.append(c);
            }
        }
        return builder.toString();
    }

    /**
     * 转换特殊字符
     * @param c
     * @return
     */
    private static char transformNextChar(char c) {
        switch (c) {
            case '\\':
                return '\\';
            case '\"':
                return '\"';
            case 'n':
                return '\n';
            case 't':
                return '\t';
        }
        return c;
    }
}
